#include "sock.hpp"
#include <poll.h>
#define NUM 1024
struct pollfd arr_rfds[NUM];
void Recv(int fd)
{
  char buffer[NUM];
  memset(buffer, 0, NUM);
  ssize_t s = recv(fd, buffer, NUM - 1, 0);
  if (s > 0)
  {
    cout << buffer << endl;
  }
  if (s == 0)
  {
    cout << "关闭连接" << endl;
    close(fd);
    for (size_t i = 0; i < NUM; i++)
    {
      if (arr_rfds[i].fd == fd)
        arr_rfds[i].fd = arr_rfds[i].events = -1;
    }
  }
  if (s < 0)
  {
    cout << "recv fail" << strerror(errno) << endl;
  }
}
void handlevent(const sock &s)
{
  if (arr_rfds[0].revents == POLLIN)
  {
    int fd = s.Accept();
    for (size_t i = 1; i < NUM; i++)
    {
      if (arr_rfds[i].fd == -1)
      {
        arr_rfds[i].fd = fd;
        arr_rfds[i].events = POLLIN;
        break;
      }
    }
  }
  for (size_t i = 1; i < NUM; i++)
  {
    if (arr_rfds[i].revents == POLLIN)
      Recv(arr_rfds[i].fd);
  }
}
int main()
{
  // 创建套接字
  sock s;
  s.Bind();
  s.Listen();
  // 添加listensock套接字
  arr_rfds[0].fd = s._listensock;
  arr_rfds[0].events = POLLIN;
  for (size_t i = 1; i < NUM; i++)
    arr_rfds[i].events = arr_rfds[i].fd = -1;
  // 获取链接
  while (true)
  {
    int n = poll(arr_rfds, NUM, -1);
    switch (n)
    {
    case -1:
      cout << "poll fail" << strerror(errno) << endl;
      break;
    case 0:
      cout << "timeout..." << endl;
      break;
    default:
      handlevent(s);
      break;
    }
  }
  return 0;
}
